<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>灯控系统</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	
	<link rel="stylesheet" href="${pageContext.request.contextPath}/css/bootstrap.min.css">
	<link rel="stylesheet" href="${pageContext.request.contextPath}/css/style.css">
	
	<%-- <script  src="${pageContext.request.contextPath}/js/jquery/jquery-3.1.1.min.js" type="text/javascript"></script> --%>
	<!-- <script type="text/javascript" src="http://webapi.amap.com/maps?v=1.3&key=您申请的key值"></script> -->
	<script type="text/javascript" src="http://webapi.amap.com/maps?v=1.4.0&key=5c7319868e7c245b3bd8f8b25d81fb20"></script>
	<script src="http://webapi.amap.com/ui/1.0/main.js?v=1.0.11"></script>
	
	<script src="${pageContext.request.contextPath}/js/jquery-1.12.4.min.js"></script>
	<!-- bootstrap 引入 -->
	<script src="${pageContext.request.contextPath}/js/tether.min.js"></script>
	<script src="${pageContext.request.contextPath}/js/popper.min.js"></script>
	<script src="${pageContext.request.contextPath}/js/bootstrap.min.js"></script>
	<!-- 引入弹窗 layer -->
	<script src="${pageContext.request.contextPath}/js/layer/layer.js"></script>
	<script src="${pageContext.request.contextPath}/js/page/common.js"></script>
	<script src="${pageContext.request.contextPath}/js/echarts-all-3.js"></script>
	<script src="${pageContext.request.contextPath}/js/page/home.js"></script>
	
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

	<style type="text/css">
		body{margin:0;padding: 0;min-height: 768px;min-width: 1024px;}
		.topdiv{height: 52px;background-color: white;}
		.logodiv{height:52px;width: 200px;float: left; background-image:url("${pageContext.request.contextPath}/img/login/logo.png");background-position: 10% 30%;}
		.selectedcss{border-bottom-color: grey !important;}
		.menu{height:50px;cursor: pointer;float:left;}
		.menu div{height:50px;width:100px;float: left;  background-color:lightgreen; border-color: white;border-style: solid;border-width: 2px;}
		.menu div:HOVER{border-color: green;}
		.logininfo{height:52px;width:100px;float:right;background-color:lightgrey;}
		.content{margin-top:0px;border-top-color: black;border-top-style: solid;border-top-color: grey;}
		.clickpointer{cursor:pointer;}
	</style>
	
	<script type="text/javascript">
		function clickmenu(menuitem,srcStr) {
			$("#menudiv").children().each(function(i,dom) {
				$(dom).removeClass("selectedcss");
			});
			
			$(menuitem).addClass("selectedcss");
			
			$("#mainframe").attr("src",srcStr);
		}
	</script>
  </head>
  
  <body>
  		<div class="header">
		<div class="left header-logo"><img class="header-logo-img" src="images/header_logo.png" /></div>
		<div class="right header-nav">
			<a class="nav-link active" href="${pageContext.request.contextPath }/main.do">
				<i class="icon icon-home"></i>
				<span class="link-text">主页</span>
			</a>
			<c:if test="${menubean.menu1 }">
			<a class="nav-link" href="${pageContext.request.contextPath }/showDevice.do">
				<i class="icon icon-install"></i>
				<span class="link-text">安装</span>
			</a>
			</c:if>
			<c:if test="${menubean.menu2 }">
			<a class="nav-link" href="${pageContext.request.contextPath}/showConfig.do">
				<i class="icon icon-config"></i>
				<span class="link-text">配置</span>
			</a>
			</c:if>
			<c:if test="${menubean.menu3 }">
			<!-- <a class="nav-link" href="operation.html">
				<i class="icon icon-operation"></i>
				<span class="link-text">操作</span>
			</a> -->
			<a class="nav-link" href="${pageContext.request.contextPath}/data.do">
				<i class="icon icon-data"></i>
				<span class="link-text">数据</span>
			</a>
			</c:if>
			<%-- <c:if test="${menubean.menu4 }">
			<a class="nav-link" href="history.html">
				<i class="icon icon-history"></i>
				<span class="link-text">历史</span>
			</a>
			</c:if> --%>
			<c:if test="${menubean.menu4 }">
			<a class="nav-link" href="${pageContext.request.contextPath}/faultList.do">
				<i class="icon icon-malfunction"></i>
				<span class="link-text">故障</span>
			</a>
			</c:if>
			<c:if test="${menubean.menu5 }">
			<a class="nav-link" href="${pageContext.request.contextPath}/showUserList.do">
				<i class="icon icon-customer-management"></i>
				<span class="link-text">客户管理</span>
			</a>
			</c:if>
			<c:if test="${menubean.menu6 }">
			<a class="nav-link" href="${pageContext.request.contextPath}/statusList.do">
				<i class="icon icon-status"></i>
				<span class="link-text">状态</span>
			</a>
			</c:if>
			<c:if test="${menubean.menu7 }">
			<a class="nav-link" href="${pageContext.request.contextPath}/currentList.do">
				<i class="icon icon-malfunction"></i>
				<span class="link-text">电流</span>
			</a>
			</c:if>
			<a class="nav-link" href="${pageContext.request.contextPath}/logout.do">
				<i class="icon icon-out"></i>
				<span class="link-text">退出</span>
			</a>
			<div class="clear"></div>
		</div>
		<div class="clear"></div>
	</div>

	<div class="block20"></div>
	<div class="container-fluid" id="mapdiv1">
		<div class="row" id="mapdiv2">
			<div class="col-lg-7 col-md-12" id="homeArticle">
				<div class="bg-white home-map-box" id="mapShowDiv">
					<div class="map-oper">
						<a href="javascript:;" id="pageViewBtn" data-view="small" class="screen-btn"></a>
					</div>
					<!-- class="home-map" -->
					<div  class="home-map" id="homeMap">
						<div class="map-div" id="dituContent"></div>
					</div>
				</div>
			</div>
			<div class="col-lg-5 col-md-12" id="homeSide">
				<div class="padding20 bg-white">
				<div class="mui-panel blue-panel side-install">
					<div class="panel-title side-install-title">
						<span class="left left-title">安装</span>
						<span class="right right-title">状态</span>
						<div class="clear"></div>
					</div>
					<div class="panel-content side-install-cont">
						<div class="left isntall-left-content">
							<select class="select all-select" id="dtuselect" onchange="changeData()">
								<option value="0">所有</option>
								<c:forEach items="${dtuList }" var="dtu">
								<option value="${dtu.dtuId }">${dtu.panId }</option>
								</c:forEach>
							</select>
								<ul class="install-list">
									<li><i class="icon icon-concentrator"></i>集中器数量:<span id="dtucount">0</span></li>
									<li><i class="icon icon-lightpole"></i>路灯数量:<span id="lightcount">0</span></li>
									<li><i class="icon icon-potencial"></i>P在线数量:<span id="onlinecount">0</span></li>
									<li><i class="icon icon-fecha"></i>故障数量:<span id="faultcount">0</span></li>
							</ul>
						</div>
							<div class="right">
								<div id="chartHomeCount" class="chart-home-count"></div>
							</div>
							<div class="clear"></div>
						</div>
					</div>
					<div class="block15"></div>
					<div class="home-weather" id="homeWeather">
						<div class="weather-info left">
							<!-- <img src="images/weather_status_01.png" class="left"> -->
							<div class="left">
							<iframe style="width:300;height:60;" scrolling="no" frameborder="0" src="http://i.tianqi.com/index.php?c=code&id=12&icon=1&num=2">
							</iframe>
							<!-- 	<div class="info-text">多云</div>
								<div class="info-number">23 ~ 15℃</div> -->
							</div>
							<div class="clear"></div>
						</div>
						<span class="weather-date left">日期：<b>${nowdate}</b></span>
						<div class="clear"></div>
					</div>
					<div class="block15"></div>
					<div class="home-side-card side-card-green side-emission-reduction">
						<i class="icon icon-co2"></i>
						<p class="info info-space-row info-main-row">这些设备减少CO<font size="1">2</font>排放量</p>
						<p class="info info-space-row"><b class="important-number">${co2 }</b>gr.de CO<font size="1">2</font></p>
						<span class="prop-text">减排</span>
					</div>
					
					<div class="block15"></div>
					<div class="home-side-card side-card-orange side-energy-saving">
						<i class="icon icon-level"></i>
						<p class="info info-space-row info-main-row">CO<font size="1">2</font>减排量排名</p>
						<p class="info info-space-row" style="font-size:24px;">第<b class="important-number">${co2Order}</b>名</p>
						<span class="prop-text">排名</span>
					</div>

				</div>
			</div>
			<div class="clear"></div>
		</div>
	</div>
  </body>
  
  
  <script type="text/javascript">
    //创建和初始化地图函数：
    function initMap(){
        createMap();//创建地图
        addMapControl();//向地图添加控件
        //addMarker();//向地图中添加marker
    }
    
    //创建地图函数：
    function createMap(){
    	var map = new AMap.Map('dituContent', {
    	    resizeEnable: true,
    	    zoom:4,
    	    center: [108.842639,34.271511]        
    	});
    	
    	//119.423443,32.400921
    	
        window.map = map;//将map变量存储在全局 
    }
    
  	//标注点数组
  	var markerArr = eval(${locationJson});
	
	var infoWindow = new AMap.InfoWindow();
  
	function showStatus(e, point){
		var contentData = "";
		// 获取路灯当前最新状态
		$.ajax({
			type : "POST",
			url : "${pageContext.request.contextPath }/queryLightLatestStatus.do",
			async: false,
			dataType : "json",
			data : {
				lightId : point.data.lightId
			},
			success : function(data) {
				console.log(data);
				if(data.success==0) {
					console.log(data.success);
					contentData += "项目编号:" + data.data.panId + "<br>";
					contentData += "设备编号:" + data.data.lightNum + "<br>";
					contentData += "上报时间:" + data.data.collectTime + "<br>";
					contentData += "状态:";
					
					if(data.data.statusCode=='10') {
						contentData +=  "空闲<br>";
					}else if(data.data.statusCode=='20') {
						contentData +=  "充电<br>";
					}else if(data.data.statusCode=='30') {
						contentData +=  "放电-灯灭<br>";
					}else if(data.data.statusCode=='31') {
						contentData +=  "放电-灯亮<br>";
					}else if(data.data.statusCode=='40') {
						contentData +=  "放电结束<br>";
					}else if(data.data.statusCode=='A1') {
						contentData +=  "欠压<br>";
					}else if(data.data.statusCode=='A2') {
						contentData +=  "开路<br>";
					}else if(data.data.statusCode=='A3') {
						contentData +=  "过载<br>";
					}else if(data.data.statusCode=='A4') {
						contentData +=  "峰值配置错误<br>";
					}else if(data.data.statusCode=='A5') {
						contentData +=  "电池接反<br>";
					}
					
					contentData += "当前温度（℃）:" + data.data.temperature + "<br>";
					contentData += "太阳板电压（V）:" + data.data.solarPanelVol + "<br>";
					contentData += "蓄电池电压（V）:" + data.data.batteryVol + "<br>";
					contentData += "充电电流（mA）:" + data.data.chargeCurrent + "<br>";
					contentData += "放电电流（mA）:" + data.data.workCurrent + "<br>";
					contentData += "放电电压（V）:" + data.data.workVol + "<br>";
					contentData += "总充电数（Ah）:" + data.data.chargeCount + "<br>";
					contentData += "总放电数（Ah）:" + data.data.workCount + "<br>";
				}else {
					contentData = "对不起，目前该设备还没有状态上送";
				}
			}
		});
		
		infoWindow.setContent(contentData);
		
		var location = point.data.point.split("|");
      	var positon = {lat: location[1], lng: location[0], N: location[0], Q: location[1]};
      	infoWindow.open(map, positon);
  	}
    
    function initPage(DistrictCluster, PointSimplifier, $, utils) {
    	var groupStyleMap = {
                '0': {
                    pointStyle: {
                    	content: PointSimplifier.Render.Canvas.getImageContent(
                                './img/map/light_on.png', onIconLoad, onIconError),
                        width: 50,
                        height: 50,
                        //定位点为中心
                        offset: ['-50%', '-50%'],
                        fillStyle: null
                    }
                },
                '1': {
                    pointStyle: {
                    	content: PointSimplifier.Render.Canvas.getImageContent(
                                './img/map/light_off.png', onIconLoad, onIconError),
                        width: 50,
                        height: 50,
                        //定位点为中心
                        offset: ['-50%', '-50%'],
                        fillStyle: null
                    }
                }
        };
    	var pointSimplifierIns = new PointSimplifier({
            map: map, //所属的地图实例
            autoSetFitView: true, //禁止自动更新地图视野
            zIndex: 110,
            getPosition: function(item) {

                if (!item) {
                    return null;
                }
                
                console.log(item.point);

                var parts = item.point.split('|');

                //返回经纬度
                return [parseFloat(parts[0]), parseFloat(parts[1])];
            },
            getHoverTitle: function(dataItem, idx) {
                return dataItem.content;
            },
            renderConstructor: PointSimplifier.Render.Canvas.GroupStyleRender,
            renderOptions: {
                //点的样式
                pointStyle: {
                	content: PointSimplifier.Render.Canvas.getImageContent(
                            './img/map/light_on.png', onIconLoad, onIconError),
                    width: 50,
                    height: 50,
                    //定位点为中心
                    offset: ['-50%', '-50%'],
                    fillStyle: null
                },
                getGroupId: function(item, idx) {
                	// 返回开关灯情况
                    return item.state;
                },
                groupStyleOptions: function(gid) {
                    return groupStyleMap[gid];
                }
            }
        });
    	
    	pointSimplifierIns.on("pointClick",function(event,point) {
    		showStatus(event,point);
    	});
    	
    	function onIconLoad() {
            pointSimplifierIns.renderLater();
        }

        function onIconError(e) {
            alert("图片加载失败！");
        }
        
        function MyRender(distClusterIns, opts) {
            //直接调用父类的构造函数
            MyRender.__super__.constructor.apply(this, arguments);
        }

        //继承默认引擎
        utils.inherit(MyRender, DistrictCluster.Render.Default);

        utils.extend(MyRender.prototype, {
            drawFeaturePolygons: function(ctx, polygons, styleOptions, feature, dataItems) {
                //调用父类方法
                MyRender.__super__.drawFeaturePolygons.apply(this, arguments);

                //直接绘制聚合信息
                this.drawMyLabel(feature, dataItems);
            },
            _initContainter: function() {
                //调用父类方法
                MyRender.__super__._initContainter.apply(this, arguments);

                //创建一个新的canvas
                this._createCanvas('mylabel', this._container);
            },
            drawMyLabel: function(feature, dataItems) {

                var pixelRatio = this.getPixelRatio(); //高清下存在比例放大

                var containerPos = map.lngLatToContainer(feature.properties.centroid || feature.properties.center);

                var labelCtx = this._getCanvasCxt('mylabel');

                //文字的中心点
                var centerX = containerPos.getX() * pixelRatio,
                    centerY = containerPos.getY() * pixelRatio;

                labelCtx.save();

                labelCtx.font = 14 * pixelRatio + 'px 微软雅黑';
				if(dataItems.length<1) {
                	return;
                }
                var text = feature.properties.name + ' (' + dataItems.length + ')';

                var textMetrics = labelCtx.measureText(text);

                var halfTxtWidth = textMetrics.width / 2;

                labelCtx.fillStyle = '#3366cc';
                //绘制一个蓝色背景
                labelCtx.fillRect(centerX - halfTxtWidth - 3 * pixelRatio,
                    centerY - 11 * pixelRatio,
                    textMetrics.width + 6 * pixelRatio,
                    22 * pixelRatio);

                labelCtx.fillStyle = '#ffffff';
                labelCtx.textBaseline = 'middle';
                labelCtx.fillText(text, centerX - halfTxtWidth, centerY);
                
                labelCtx.restore();
            }
        });

        var distCluster = new DistrictCluster({
            map: map, //所属的地图实例
            zIndex:300,
            getPosition: function(item) {

                if (!item) {
                    return null;
                }

                var parts = item.point.split('|');

                //返回经纬度
                return [parseFloat(parts[0]), parseFloat(parts[1])];
            },
            boundsQuerySupport:true,
          	//使用自定义的引擎类
            renderConstructor: MyRender,
            renderOptions: {
                //不再使用聚合标注
                getClusterMarker: null,
                //点击区划面后切换到子级区划
                featureClickToShowSub: true,
                //featureEventSupport: true,
                //clusterMarkerEventSupport: true,
                //clusterMarkerEventNames: ['click', 'rightclick', 'mouseover', 'mouseout'],
              	//基础样式
                featureStyle: {
                    fillStyle: 'rgba(100,170,0,0.01)', //填充色
                    lineWidth: 1, //描边线宽
                    strokeStyle: 'rgb(31, 119, 180)', //描边色
                    //鼠标Hover后的样式
                    hoverOptions: {
                        fillStyle: 'rgba(199, 233, 192, 0.01)'
                    }
                },
              	//特定区划级别的默认样式
                featureStyleByLevel: {
                    //全国
                    country: {
                        fillStyle: 'rgba(49, 163, 84, 0.01)'
                    },
                    //省
                    province: {
                        fillStyle: 'rgba(116, 196, 118, 0.01)'
                    },
                    //市
                    city: {
                        fillStyle: 'rgba(161, 217, 155, 0.01)'
                    },
                    //区县
                    district: {
                        fillStyle: 'rgba(199, 233, 192, 0.01)'
                    }
                }
            }
            
        });

        window.distCluster = distCluster;
        
        function refresh() {
            //获取 pointStyle
            var pointStyle = pointSimplifierIns.getRenderOptions().pointStyle;

            //根据当前zoom调整点的尺寸
            pointStyle.width = pointStyle.height = 2 * Math.pow(1.2, map.getZoom() - 3);

            var zoom = map.getZoom();
            if (zoom > 10) {
                distCluster.hide();
                pointSimplifierIns.show();
            } else {
            	distCluster.show();
            	pointSimplifierIns.hide();
            }
        }

        map.on('zoomend', function() {
            refresh();
        });

        refresh();
        
        distCluster.setData(markerArr);
        pointSimplifierIns.setData(markerArr);

        /* $('<div id="loadingTip">加载数据，请稍候...</div>').appendTo(document.body);
        $.get('http://a.amap.com/amap-ui/static/data/10w.txt', function(csv) {

            $('#loadingTip').remove();

            var data = csv.split('\n');

            distCluster.setData(data);
            pointSimplifierIns.setData(data);
        }); */
    }

    //加载相关组件
    AMapUI.load(['ui/geo/DistrictCluster', 'ui/misc/PointSimplifier', 'lib/$', 'lib/utils'], function(DistrictCluster, PointSimplifier, $, utils) {
        //启动页面
        initPage(DistrictCluster, PointSimplifier, $, utils);
        //initPage(PointSimplifier, $);
    });
    
    //地图控件添加函数：
    function addMapControl(){
    	AMap.plugin(['AMap.ToolBar','AMap.Scale','AMap.OverView'],
    		    function(){
    		        map.addControl(new AMap.ToolBar());
    		        map.addControl(new AMap.Scale());
    		        map.addControl(new AMap.OverView({isOpen:true}));
    		});
    }
    
    /* var infoWindow = new AMap.InfoWindow();
    
    function markerClick(e){
        infoWindow.setContent(e.target.content);
        infoWindow.open(map, e.target.getPosition());
    }
    
    //创建marker
    function addMarker(){
        for(var i=0;i<markerArr.length;i++){
            var json = markerArr[i];
            var p0 = json.point.split("|")[0];
            var p1 = json.point.split("|")[1];
            
            var iconImg = null;
            if(json.state==1) {
				iconImg = createIcon();
            }else {
            	iconImg = createIcon1();
            }
            
            var marker = new AMap.Marker({
            	icon : iconImg,
                position: [p0, p1],
                offset : new AMap.Pixel(-12,-12)
            });
            
            marker.content=json.title + "<br>" +json.content;
            marker.setMap(map);
            marker.on('click', markerClick);
        }
    } 
    
    //创建一个Icon
    function createIcon(){
        return "http://www.365ctrl.com/img/map/light_gray.png";
    }
    
    //创建一个Icon
    function createIcon1(){
        return "http://www.365ctrl.com/img/map/light_orange.png";
    }*/
    
    $(document).ready(function() {
	    initMap();//创建和初始化地图
	    changeData();
    });
    
    function changeData() {
    	var dtuId = $("#dtuselect").val();
    	$.ajax({
			type : "POST",
			url : "${pageContext.request.contextPath }/queryCountData.do",
			async: false,
			dataType : "json",
			data : {
				dtuId : dtuId
			},
			success : function(data) {
				if(data.success==0) {
					$("#dtucount").text(data.dtucount);
					$("#lightcount").text(data.lightcount);
					$("#onlinecount").text(data.onlinecount);
					$("#faultcount").text(data.faultcount);
					
					showHomeEchart(data.onlinecount,data.faultcount);
				}
			}
		});
    }
    
    $("#pageViewBtn").click(function(){
        if($(this).hasClass("all-screen-btn")) {
            $(this).removeClass("all-screen-btn");
            $("#homeArticle").addClass("col-lg-7");
            $("#homeArticle").removeClass("height-all");
           /*  $("#mapdiv1").removeClass("height-all");
            $("#mapdiv2").removeClass("height-all"); */
            $("#mapShowDiv").removeClass("all-screen-map");
            scroll(0,Math.round(0));
        } else {
            $(this).addClass("all-screen-btn");
            /* $("#mapdiv1").addClass("height-all");
            $("#mapdiv2").addClass("height-all"); */
            $("#homeArticle").removeClass("col-lg-7");
            $("#homeArticle").addClass("height-all");
            $("#mapShowDiv").addClass("all-screen-map");
            
            //var scrollHeight=document.body.scrollHeight/2;
            var top = $("#homeArticle").offset().top;
            scroll(0,Math.round(top));
        }
    });
</script>
</html>
